package com.example.hans.databaseandroid;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.BoringLayout;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import tools.LoginReplayPacket;
import tools.LogonPacket;
import tools.LogonReplyPacket;
import tools.Service;
import tools.Util;

/**
 * 注册活动
 */
public class CreateAccountActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText mETName;
    private EditText mETPassword;
    private Button mBtuCreateAccount;
    private String mName;
    private String mPassword;
    private List<User> users;
    private static String TAG = "CreateAccountActivity";
    LogonReplyPacket loRPacket = new LogonReplyPacket();


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    if (loRPacket.getReply().equals(Service.SUCCESS)) {
                        //注册成功
                        Intent intent = new Intent(CreateAccountActivity.this,MainActivity.class);
                        startActivity(intent);

                    } else {
                        //用户名重复
                        showEnrollFail("该用户已存在");

                    }
                }
                default: {
                    super.handleMessage(msg);
                }
            }
        }
    };


    public void initView() {
        mETName = findViewById(R.id.et_name);
        mETPassword = findViewById(R.id.et_password);
        mBtuCreateAccount = findViewById(R.id.btn_create_account);


        new Thread(mSocketRunnable).start();
        mBtuCreateAccount.setOnClickListener(this);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_account_layout);

        initView();

    }
    boolean mRun = true;

    private Socket mSocket;
    private Runnable mSocketRunnable = new Runnable() {
        @Override
        public void run() {
            Log.d("ChatActivity", "Thread start run");
            mRun = true;
            try {
                Log.d("ChatActivity", "start connect to 10.0.2.2");
                Socket connection = new Socket("192.168.5.2", 2018);
                Log.d("ChatActivity", "after connect to 10.0.2.2");
                OutputStream out = connection.getOutputStream();
                InputStream in = connection.getInputStream();
                byte[] readBuffer = new byte[1024];
                while(mRun) {
                    if (isPress) {
                        LogonPacket packet = new LogonPacket();
                        packet.userName = mName;
                        packet.password = mPassword;
                        out.write(packet.serialize());
                        out.flush();
                        int length = in.read(readBuffer);
                        int packetType = Util.bytes2int(readBuffer, 4);
                        if (packetType == Service.PACKET_TYPE.S2C_LOGON) { //注册的返回包
//                            LogonReplyPacket reply = new LogonReplyPacket();
                            loRPacket.unserialize(readBuffer);
                            Log.d(TAG,loRPacket.getName());
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = loRPacket;
                            mHandler.sendMessage(msg);
                        }
                        isPress = false;
                    }


                    Thread.sleep(1000);
                }

                mSocket.close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };



    public boolean isEmpty(String string) {
        if (string != null || string.equals("")) return false;
        return true;
    }

    private boolean isPress = false;

    @Override
    public void onClick(View view) {
//        if (flag) {
//            LitePal.getDatabase();
//            flag = false;
//        }
        switch (view.getId()) {
            case R.id.btn_create_account: {

                getData();
                verify();

                isPress = true;

//                users = DataSupport.where("name = ?",mName).find(User.class);
//                if (users.size() >= 1) {
//                    showEnrollFail("该用户已存在");
//                    break;
//                }
//
//                User user = new User();
//                user.setName(mName);
//                user.setPassword(mPassword);
//                user.save();
//
//                Intent intent = new Intent(this,MainActivity.class);
//                startActivity(intent);
                break;
            }
            default:
        }
    }

    public void showEnrollFail(String msg) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("注册失败");
        dialog.setMessage(msg);
        dialog.setCancelable(false);
        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.setNegativeButton("再试一次", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.show();
    }

    public void getData() {
        //获取输入的用户名和密码
        mName = mETName.getText().toString();
        mPassword = mETPassword.getText().toString();
    }

    public void verify() {

    }
}
